using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using UnityEditor.SceneManagement;
using UnityEngine.SceneManagement;
using XYRenderPipelines.Runtime;
using XYTerrain.Runtime;
using Debug = UnityEngine.Debug;
using Scene = UnityEngine.SceneManagement.Scene;


namespace XYTerrain.Editor
{
    

    public class TerrainLayerSelection : EditorWindow{

         public static EditorSceneData sceneData
         {
             get
             {
                 if (_sceneData == null)
                 {
                     var objPath = AssetDatabase.FindAssets("t:EditorSceneData");
                     _sceneData = AssetDatabase.LoadAssetAtPath<EditorSceneData>(AssetDatabase.GUIDToAssetPath(objPath[0]));
                 }
                 return _sceneData;
             }
         }
         
        public static EditorSceneData _sceneData;
        
        /// <summary>
        /// 每个Terrain 的大小
        /// </summary>
        public float terrainSize = 500f;
         
        
        [MenuItem("GameObject/MoveTo", priority = 0)]
        public static void OpenWindow(MenuCommand menuCommand)
        {

            if (SceneManager.GetActiveScene().name != "EditorScene")
            {
                EditorUtility.DisplayDialog("警告","当前不在editorScene下", "ok");
                return;
            }
            if (menuCommand.context as GameObject != Selection.activeObject)
            {
                return;
            }
            var window = EditorWindow.GetWindow<TerrainLayerSelection>(true,"大变活人",true);
            window.maxSize =new Vector2(250,80);
            window.minSize=new Vector2(250,80);
            window.terrainSize = sceneData.boundSize.x;
            
            window.Show();
            window.GetLayerNames();
            window.ObjectMoveTo(Selection.transforms);
            if (window.layerNames.Length == 1)
            {
                window.Config();
            }
            
            
            
        }

        private int selectionId = 0;
        private string[] layerNames;
        private Dictionary<Vector2Int, List<Transform>> waitToMove;


        private void ObjectMoveTo(Transform[] transforms)
        {
             
            waitToMove = new Dictionary<Vector2Int, List<Transform>>();
            //  分类所有节点
            foreach (var i in transforms)
            {
                var vec =  GetBoundNum(i);
                if (!waitToMove.ContainsKey(vec))
                {
                   waitToMove.Add(vec,new List<Transform>()); 
                }
                waitToMove[vec].Add(i);
            } 
            
            
        }

        private void OnGUI()
        {
            DrawTerrainSelection();
        }


        private void GetLayerNames()
        {
            var loaderWindow = EditorWindow.GetWindow<EditorSceneLoader>();
            List<string> layerList = new List<string>();
            for (int i = 0; i<sceneData.collectionManagers.Count  ;i++)
            {
                if (loaderWindow.loaderData.layerSelecter[i])
                {
                    var layerMsg = EditorSceneLoader.sceneData.collectionManagers[i];
                    layerList.Add(layerMsg.prefixScene);
                }
            }
            

            layerNames = layerList.ToArray();
        }
        
        
        public  Vector2Int GetBoundNum(Transform t)
        {
            var pos = t.transform.position;
            int x = Mathf.FloorToInt(pos.x / terrainSize);
            int z = Mathf.FloorToInt(pos.z / terrainSize);

            return new Vector2Int(x, z);
        }
        
        
        
        private void DrawTerrainSelection()
        {
            EditorGUILayout.LabelField("选择目标层",EditorStyles.largeLabel);
            EditorGUILayout.BeginVertical(EditorStyles.helpBox);
            selectionId = EditorGUILayout.Popup(selectionId, layerNames);
            EditorGUILayout.Space(5);
            EditorGUILayout.BeginHorizontal();
            if( GUILayout.Button("确定"))
            {
                Config();
            }
            if (GUILayout.Button("取消"))
            {
                CloseView();
            }
            EditorGUILayout.EndHorizontal();
            EditorGUILayout.EndVertical();
        }

        private void Config()
        {

            Scene editorScene = SceneManager.GetActiveScene();
            string sceneName =  layerNames[selectionId];
            
            var loaderWindow = EditorWindow.GetWindow<EditorSceneLoader>();
            var sceneList = loaderWindow.GetCurrentAllScene();

            
            List<Scene> scenes = new List<Scene>();
            foreach (var i in sceneList)
            {
                if (i.name.Contains(sceneName))
                {
                    scenes.Add(i);
                }
            }
            foreach (var i in waitToMove)
            {
                string targetName = $"{sceneName}_x{i.Key.x}_z{i.Key.y}";
                if(scenes.Exists((x)=>x.name==targetName))
                {
                   var targetScene = scenes.Find((x) => x.name == targetName);
                   foreach (var obj in i.Value)
                   {
                       Debug.Log(obj.name+ "移动到"+ targetName,obj);
                       SceneManager.SetActiveScene(obj.gameObject.scene);
                       obj.parent = null;
                       SceneManager.MoveGameObjectToScene(obj.gameObject,targetScene);
                       GameObject[] roots = null;
                       if (targetScene.GetRootGameObjects() == null)
                       {
                           Debug.Log(targetName+"无根节点");
                           continue;
                          
                       }
                       else
                       {
                           roots = targetScene.GetRootGameObjects();
                       }

                       bool hasRoot = false;
                       foreach (var root in roots)
                       {
                           if (root.name == targetScene.name)
                           {
                                obj.transform.parent = root.transform;
                                EditorUtility.SetDirty(obj);
                                hasRoot = true;
                                break;
                           }
                           
                       }
                       if(!hasRoot) Debug.LogWarning( targetName+"场景根节点信息有误， 场景根节点名称应与场景名保持一致");
                       // 加入名称检查 以免使用者地块场景根物体信息有误
                       // TODO遍历所有子节点进行求中心坐标 现在很多策划存在根节点信息使用（0,0,0)作为标准
                       
                   }
                        
                }else Debug.LogWarning("当前物体属于 "+ targetName+"但场上不存在该场景");
                
                
            }

            SceneManager.SetActiveScene(editorScene);
            EditorSceneManager.SaveOpenScenes();
            CloseView(); 
        }

        private void CloseView()
        {
            layerNames = null;
            selectionId = 0;
            Close();  
        }
        
    }
    

}